from playwright.sync_api import Page
import json
from src.utils.get_project_root import get_project_root


def scrape_and_save(page: Page, url, page_name="login_page"):
    """

    :param page:
    :param url:
    :param page_name:
    :return: file_path
    """
    config_dir = get_project_root() / "config" / 'page_content_data' / page_name
    page.goto(url)
    page.wait_for_load_state("networkidle")  # 等待页面完全加载
    # === 1. 获取完整 HTML 内容（DOM 树）===
    page_content = page.content()
    page_evaluate = page.evaluate("document.documentElement.outerHTML")
    with open(f"{config_dir}.json", "w", encoding="utf-8") as f:
        json.dump(page_evaluate, f, ensure_ascii=False, indent=2)
    print(f"✅ JSON 已保存到: {config_dir}.json")

    with open(f"{config_dir}.html", "w", encoding="utf-8") as f:
        f.write(page_content)
    print(f"✅ HTML 已保存到: {config_dir}.html")
    return f"{config_dir}.json"


def save_page_content(page_evaluate, page_name=None):
    config_dir = get_project_root() / "config" / 'page_content_data' / page_name
    # === 1. 获取完整 HTML 内容（DOM 树）===
    with open(f"{config_dir}.json", "w", encoding="utf-8") as f:
        json.dump(page_evaluate, f, ensure_ascii=False, indent=2)
    print(f"✅ JSON 已保存到: {config_dir}.json")
    return f"{config_dir}.json"


if __name__ == '__main__':
    url = "https://team.pescms.com/?g=Team&m=Login&a=index&back_url=Lw=="
    scrape_and_save(url)
